package cn.ubest.mvvmcore.http.converter;

/**
 * Created by maoqi on 2021/1/14.
 */

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import cn.ubest.mvvmcore.http.HttpCode;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by maoqi on 2018/10/9.
 */
public final class CustomJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomJsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(value.byteStream()));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        String json = buffer.toString();

        try {
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.getInt("code");
            if (code != HttpCode.REQ_SUCCESSFUL) {
                jsonObject.remove("data");
                return adapter.fromJson(jsonObject.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            value.close();
        }
        return adapter.fromJson(json);

//        try {
//            T result = adapter.read(jsonReader);
//            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
//                throw new JsonIOException("JSON document was not fully consumed.");
//            }
//            return result;
//        } finally {
//            value.close();
//        }


    }
}
